package com.xx.springsecuritydemo.main.security;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * 自定义访问决策
 */
@Component
public class CustomAccessDecisionManager implements AccessDecisionManager {
    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
        if (configAttributes == null) {
            return; // 如果没有权限配置，直接放行
        }

        for (ConfigAttribute attribute : configAttributes) {
            String requiredRole = attribute.getAttribute();

            // 如果只要求认证即可访问
            if ("ROLE_AUTHENTICATED".equals(requiredRole)) {
                // 检查是否为匿名用户
                if (authentication == null || "anonymousUser".equals(authentication.getPrincipal())) {
                    throw new AccessDeniedException("需要登录后访问");
                }
                return; // 已登录用户允许访问
            }

            // 校验用户是否具备所需权限
            if (authentication.getAuthorities().stream()
                    .anyMatch(grantedAuthority -> grantedAuthority.getAuthority().equals(requiredRole))) {
                return; // 用户具备所需权限，允许访问
            }
        }

        // 如果没有匹配到任何权限，拒绝访问
        throw new AccessDeniedException("权限不足");
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return false;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return false;
    }
}
